<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="/js/jquery-3.2.1.min.js"></script>
    <script src="/js/bootstrap/bootstrap.min.js"></script>
    <script src="/js/jquery.hammer/hammer.min.js"></script>
    <script src="/js/bootstrap.table/bootstrap-table.min.js" type="text/javascript"></script>
    <script src="/js/bootstrap.table/bootstrap-table-zh-CN.min.js" type="text/javascript"></script>
    <script src="/js/jquery.ztree.all.min.js"></script>
    <script src="/js/dialog.js"></script>
    <script src="/js/comm.js" type="text/javascript"></script>

    <link href="/css/bootstrap/bootstrap.css" rel="stylesheet" />
    <link href="/css/bootstrap.table/bootstrap-table.min.css"/>
    <link href="/css/dialog.css" rel="stylesheet" />
    <link href="/css/zTreeStyle.css" rel="stylesheet" />
    <link href="/css/common.css" rel="stylesheet" />
</head>
<style type="text/css">
    a,a:hover,a:visited,a:link{
        cursor: pointer;
        text-decoration: none;
    }
</style>
<script type="text/javascript">
    var zTreeObj;
    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
    var setting = {
        async: {
            enable: true,
            type: "post",
            url: "/system/getUserRolesList.do",
            autoParam: ["id"]
        },
        check: {
            enable: true,
            chkStyle: "checkbox"
        },
        callback: {
            onAsyncSuccess: asyncSuccess
        }
    };
    var nodes = [
        { "id":"",
            "name":"角色",
            "isParent" :true,
            "nocheck":true,
            open:true,
            children: []
        }
    ]

$(function () {
    initTable();
    $("#btn_add").on("click",function () {
        window.location.href = "editUserInfo.html"
    })

    $("#btn_edit").on("click", function () {
        var valueInfo = $('#mytab').bootstrapTable('getSelections');
        if(valueInfo!=null&&valueInfo!=""&&valueInfo.length>0){
            window.location.href = "editUserInfo.html?btnPurid="+btnPurid+"&id="+valueInfo[0].id;
        }else {
            promptDail("请选择一条数据！");
        }
    })

    $("#btn_delete").on("click",function () {
        var valueInfo = $('#mytab').bootstrapTable('getSelections');
        if(valueInfo!=null&&valueInfo!=""&&valueInfo.length>0){
            deleteUserInfo(valueInfo[0].id);
        }else {
            promptDail("请选择一条数据！");
        }
    })

});
    
function deleteUserInfo(userId) {

    dialog({
        title: "删除",
        content: "确认删除该用户？",
        width: '300px',
        okValue: "确定",
        ok : function () {
            var b = false;
            $.ajax({
                url: "/system/deleteUsers.do",
                data: {"userId":userId},
                dataType:"json",
                type:"POST",
                async: false,
                success:function (datas) {
                    b = datas.value;
                }
            })
            if(b){
                okDail("删除成功！");
                initTable();
            }else {
                errorDail("删除失败！");
            }

        },
        cancelValue: '取消',
        cancel: function () {}
    }).showModal();
}

function initTable() {
    //先销毁表格
    $('#mytab').bootstrapTable('destroy');
    //初始化表格,动态从服务器加载数据
    $("#mytab").bootstrapTable({
        method: "post",  //使用get请求到服务器获取数据
        contentType: "application/x-www-form-urlencoded",
        url: "/system/userList.do", //获取数据的Servlet地址
        sidePagination: "server", //表示服务端请求
        queryParamsType:'',
        cache: false,
        striped: true,
        queryParams: function queryParams(params) {   //设置查询参数
            var param = {
                pageNumber: params.pageNumber,
                pageSize: params.pageSize,
                usrName : $("#usrName").val()
            };
            return param;
        }
    });
}

function editRole(ids) {
    $("#roleIds").val(ids);
    var elem = document.getElementById('editResource');
    zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, nodes);
    dialog({
        title: "角色管理",
        content: elem,
        width: '250px',
        okValue: "确定",
        ok : function () {
            var nodes = zTreeObj.getCheckedNodes(true);
            if(saveUserRole(nodes, ids)){
                promptDail("保存成功!");
                return true;
            }else {
                errorDail("保存失败!");
                return false;
            }

        },
        cancelValue: '取消',
        cancel: function () {}
    }).showModal();

}

function asyncSuccess() {
    var userId = $("#roleIds").val();
    $.post("/system/getUserRoleInfo.do",{"userId":userId},function (data) {
        if(data!=null&&data.length>0){
            for(var i=0;i<data.length;i++){
                var node = zTreeObj.getNodesByParam("id", data[i], null);
                zTreeObj.checkNode(node[0], true, true);
            }

        }
    },"json")
}

function saveUserRole(nodes, ids) {
    var b = false;
    var data = {};
    var res = "";
//    if(nodes==null||nodes.length<=0){
//        return false;
//    }
    for(var i=0;i<nodes.length;i++){
        var nodeInfo = nodes[i];
        if(!nodeInfo.isParent){
            res +=nodeInfo.id;
            if(i<nodes.length-1){
                res += ",";
            }

        }
    }
    data["userId"] = ids;
    data["roleIds"] = res;

    $.ajax({
        url: "/system/editUserRoles.do",
        data: data,
        dataType:"json",
        type:"POST",
        async: false,
        success:function (datas) {
            b = datas.value;
        }
    })

    return b;
}

function editPasswd(ids) {
    dialog({
        title: "重置密码",
        content: "确认修改密码为原始密码！",
        width: '20em',
        okValue: "确定",
        ok : function () {
            $.post("/system/editPasswd.do",{"id":ids},function (data) {
                if(data.value){
                    okDail("重置成功！");
                }else {
                    errorDail("重置失败!");
                }
            },"json")
        }
    }).showModal();

}
</script>
<body style="padding:5px;">
<div class="panel panel-default" >
    <div class="panel-heading">
        查询条件
    </div>
    <div class="panel-body form-group" style="margin-bottom:0px;">
        <form id="searchForm">
            <label class="col-sm-2 control-label" style="width: 10%;text-align: right; margin-top:5px">用户名称：</label>
            <div class="col-sm-2">
                <input type="text" class="form-control" name="usrName" id="usrName"/>
            </div>
            <div class="col-sm-1">
                <button class="btn btn-primary" id="search_btn" onclick="initTable();return false;">查询</button>
            </div>
        </form>
    </div>
</div>
<div id="toolbar" class="btn-group pull-right"  style="margin: 0px 0px 5px 0px;">
    <button id="btn_edit" type="button" class="btn btn-default btn-purview" style=" border-radius: 0">
        <span class="glyphicon glyphicon-pencil"  ></span>修改
    </button>
    <button id="btn_delete" type="button" class="btn btn-default btn-purview" >
        <span class="glyphicon glyphicon-remove" ></span>删除
    </button>
    <button id="btn_add" type="button" class="btn btn-default btn-purview">
        <span class="glyphicon glyphicon-plus" ></span>新增
    </button>
</div>
<table id="mytab" data-toggle="table" class="table table-hover table-bordered" data-single-select="true"
       data-toolbar-align="right" data-toolbar="#toolbar" data-pagination="true"  data-page-size="10"
       data-page-list="[10,20,30]" data-pagination-h-align="right" data-pagination-detail-h-align="left"
       data-pagination-loop="false" data-click-to-select="true" >
    <colgroup>
        <col style="width: 2%">
        <col style="width: 10%">
        <col style="width: 20%">
        <col style="width: 10%">
        <col style="width: 15%">
        <col style="width: 20%">
        <col style="width: 10%">
        <col style="width: 13%">
    </colgroup>
    <thead>
    <tr >
        <th data-align="center" data-valign="middle" data-checkbox="true" ></th>
        <th data-align="center" data-valign="middle" data-field="id" >id</th>
        <th data-align="center" data-valign="middle" data-field="usrname">用户名称</th>
        <th data-align="center" data-valign="middle" data-field="lgname">登录名称</th>
        <th data-align="center" data-valign="middle" data-field="usrstatus" data-formatter="initFormat">用户状态</th>
        <th data-align="center" data-valign="middle" data-field="usrphone">用户电话</th>
        <th data-align="center" data-valign="middle" data-field="description" >描述</th>
        <th data-align="center" data-valign="middle" data-formatter="initEdit">设置</th>
    </tr>
    </thead>
</table>
<div id="editResource" style="display: none;">
    <div style="width: 100%;margin-top: 10px;">
        <form class="form-horizontal" id="roleForm" role="form">
            <input id="roleIds" name="roleIds" hidden="hidden"/>
            <div style="width: 200px;height: 200px;overflow-y: auto;overflow-x: hidden">
                <ul id="treeDemo" class="ztree" style="width: 200px;height: 200px;">

                </ul>
            </div>
        </form>
    </div>
</div>
</body>
<script style="text/javascript">
    function initFormat(val, row, index) {
        if(val==1||val=="1"){
            return "有效";
        }else {
            return "无效";
        }
    }

    function initEdit(val, row, index) {
        var html = "";
        html += "<a href='javascript:void(0)' onclick='editRole("+row.id+")'>【设置角色】</a>"
        html += "<br><a href='javascript:void(0)' onclick='editPasswd("+row.id+")'>【重置密码】</a>"
        return html;
    }

</script>
</html>